package com.zbkj.admin.filter;

import cn.hutool.core.util.ObjectUtil;
import com.zbkj.common.vo.LoginUserVo;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 * token过滤器 验证token有效性
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private TokenComponent tokenComponent;

    // 定义无需Token验证的路径（按需添加）
    private static final String[] WHITELIST = {
            "/api/front/register/user",
            "/api/admin/login",
            "/swagger-ui/**"
    };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 获取当前请求路径
        String path = request.getRequestURI();

        // 检查是否在白名单中
        if (isPathExcluded(path)) {
            filterChain.doFilter(request, response);
            return; // 直接放行，不执行Token验证
        }

        // 白名单外的请求需要验证Token
        LoginUserVo loginUser = tokenComponent.getLoginUser(request);
        if (ObjectUtil.isNotNull(loginUser)) {
            tokenComponent.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 检查路径是否在白名单中
     */
    private boolean isPathExcluded(String path) {
        for (String excludedPath : WHITELIST) {
            if (path.startsWith(excludedPath)) { // 支持前缀匹配（如 /api/public/**）
                return true;
            }
        }
        return false;
    }
}
